# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import io
import os
import time
import json
import yaml
import random
import argparse
import pandas as pd
from datetime import datetime
from utils import get_logger
from utils import TASKS
import glob

os.environ["TOKENIZERS_PARALLELISM"] = "true"


def parse_args():
    # 解析--yaml-path这个参数
    parser = argparse.ArgumentParser()
    parser.add_argument("--yaml-path", type=str, default="")
    args = parser.parse_args()
    return args


def single_task_run(work_dir, dataset_cfg, model_cfg, eval_score_save_context=False):
    task_type = dataset_cfg["type"]
    task_build_cfg = {
        "type": task_type,
        "work_dir": work_dir,
        "model_cfg": model_cfg,
        "dataset_cfg": dataset_cfg,
        "eval_score_save_context": eval_score_save_context,
    }
    task = TASKS.build(task_build_cfg)
    task_score_df = task.run()
    return task_score_df


def main():
    logger = get_logger("main")
    args = parse_args()
    yaml_path = args.yaml_path
    assert yaml_path is not None and os.path.isfile(yaml_path)
    with open(yaml_path, "r") as f:
        task_config = yaml.safe_load(f)

    base_info = task_config["DEFAULT"]
    datasets = list(task_config["DATASET"].values())
    models = list(task_config["MODEL"].values())

    work_dir = base_info["work_dir"]
    task_name = base_info["task_name"]
    work_dir = os.path.join(work_dir, task_name)
    os.makedirs(work_dir, exist_ok=True)
    logger.info(f"Running Task: {task_name}, work dir: {work_dir}")

    # 运行任务
    summary_df = None
    for dataset in datasets:
        dataset_summary_df = None
        for model in models:
            task_score_df = single_task_run(work_dir, dataset, model)
            if dataset_summary_df is None:
                dataset_summary_df = task_score_df
            else:
                dataset_summary_df = pd.merge(dataset_summary_df, task_score_df,
                                              on=["dataset", "version", "metric", "mode"], how="outer")
        if summary_df is None:
            summary_df = dataset_summary_df
        else:
            summary_df = pd.concat([summary_df, dataset_summary_df], axis=0, ignore_index=True)
    # 保存结果
    summary_save_dir = os.path.join(work_dir, "summary")
    os.makedirs(summary_save_dir, exist_ok=True)
    summary_time_str = datetime.now().strftime("%Y%m%d_%H%M%S")
    summary_save_path = os.path.join(summary_save_dir, f"summary_{summary_time_str}.csv")
    summary_df.to_csv(summary_save_path, index=False)


if __name__ == "__main__":
    main()
